import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * Date: 2023-06-08
 * Time: 15:31
 */
public class JDBCSelect {
    public static void main(String[] args) throws SQLException {
        //1.创建并初始化数据源
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java107?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("123456");
        //2.建立连接
        Connection connection = dataSource.getConnection();
        //3.构造SQL
        String sql = "select * from student";
        PreparedStatement statement = connection.prepareStatement(sql);
        //4.执行SQL
        ResultSet resultSet = statement.executeQuery();
        //5.遍历结果集合
        while (resultSet.next()){
            //把resultSet想象成一个表格,同时表格这里有个光标,初始情况下光标指向表的最上面.
            //每次调用next光标往下走一行  当光标把整个表遍历完next返回false
            //当光标指向某一行的时候,就可以通过getXXX来获取当前行的数据
            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            System.out.println("id = "+ id + ", name = " + name);
        }
        //6.释放资源
        resultSet.close();//查询结果的临时表
        statement.close();
        connection.close();
    }
}
